package com.zyz.friend.service.quesiton.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zyz.common.core.enums.ResultCodeEnum;
import com.zyz.common.core.model.TableDataInfo;
import com.zyz.common.security.exception.ServiceException;
import com.zyz.friend.elasticsearch.QuestionRepository;
import com.zyz.friend.manager.QuestionCacheManager;
import com.zyz.friend.mapper.question.QuestionMapper;
import com.zyz.friend.model.question.Question;
import com.zyz.friend.model.question.dto.QuestionQueryDTO;
import com.zyz.friend.model.question.es.QuestionES;
import com.zyz.friend.model.question.vo.QuestionDetailVO;
import com.zyz.friend.model.question.vo.QuestionVO;
import com.zyz.friend.service.quesiton.IQuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class QuestionServiceImpl implements IQuestionService {

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionCacheManager questionCacheManager;

    @Override
    public TableDataInfo list(QuestionQueryDTO questionQueryDTO) {
        // 判断elasticsearch中有没有数据
        if (questionRepository.count() <= 0) {
            // 刷新es数据
            refreshQuestion();
        }
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");    // 排序
        Pageable pageable = PageRequest.of(questionQueryDTO.getPageNumber()-1, questionQueryDTO.getPageSize() ,sort); // 指定分页
        Integer difficulty = questionQueryDTO.getDifficulty();
        String keyword = questionQueryDTO.getKeyword();
        Page<QuestionES> questionESPage;
        if (difficulty == null && StrUtil.isEmpty(keyword)) {
            questionESPage = questionRepository.findAll(pageable);
        } else if (difficulty == null) {
            questionESPage = questionRepository.findByTitleOrContent(keyword, keyword, pageable);
        } else if (StrUtil.isEmpty(keyword)) {
            questionESPage = questionRepository.findQuestionByDifficulty(difficulty,pageable);
        } else {
            // 都不为空
            questionESPage = questionRepository.findByTitleOrContentAndDifficulty(keyword,keyword,difficulty,pageable);
        }

        long total = questionESPage.getTotalElements();
        if (total <= 0) {
            return TableDataInfo.empty();
        }
        List<QuestionES> content = questionESPage.getContent();
        List<QuestionVO> questionVOS = BeanUtil.copyToList(content, QuestionVO.class);
        return TableDataInfo.success(questionVOS,total);
    }

    @Override
    public QuestionDetailVO detail(Long questionId) {
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        if (questionES != null) {
            questionDetailVO = BeanUtil.copyProperties(questionES, QuestionDetailVO.class);
        }
        // questionES为空 从数据库中查询
        Question questionByDB = questionMapper.selectById(questionId);
        if (questionByDB == null) {
            log.error("题目不存在，题目id: {}",questionId);
            throw new ServiceException(ResultCodeEnum.FAILED_NOT_EXISTS);
        }
        // 刷新elasticsearch
        refreshQuestion();
        BeanUtil.copyProperties(questionByDB, questionDetailVO);
        return questionDetailVO;
    }

    @Override
    public String preQuestion(Long questionId) {
        Long CacheListSize = questionCacheManager.getListSize();
        if (CacheListSize == null || CacheListSize <= 0) {
            // 刷新cache缓存
            questionCacheManager.refreshCache();
        }
        // 从缓存中拿到questionId的下一题
        return questionCacheManager.getPreQuestionId(questionId).toString();
    }

    @Override
    public String nextQuestion(Long questionId) {
        Long CacheListSize = questionCacheManager.getListSize();
        if (CacheListSize == null || CacheListSize <= 0) {
            // 刷新cache缓存
            questionCacheManager.refreshCache();
        }
        // 从缓存中拿到questionId的下一题
        return questionCacheManager.getNextQuestionId(questionId).toString();
    }

    @Override
    public List<String> getQuestionHotList(Long size) {
        List<Long> questionHotList = questionCacheManager.getQuestionHotList(size);
        List<String> questionTitle = new ArrayList<>();
        // 根据id查询es中题目标题
        for (Long questionId : questionHotList) {
            QuestionES questionES = questionRepository.findById(questionId).orElse(null);
            questionTitle.add(questionES.getTitle());
        }
        return questionTitle;
    }

    private void refreshQuestion() {
        // 从数据库中查询
        List<Question> questionsByDB = questionMapper.selectList(new LambdaQueryWrapper<Question>());
        if (CollectionUtil.isEmpty(questionsByDB)) {
            return ;
        }
        // 赋值给es
        List<QuestionES> questionESList = BeanUtil.copyToList(questionsByDB, QuestionES.class);
        questionRepository.saveAll(questionESList);
    }
}
